<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div class="form_body">
      <el-form
        ref="formData"
        :model="formData"
        :rules="formRules"
        label-width="140px"
      >
        <el-form-item prop="labelName" label="标签名称：">
          <el-input
            v-model="formData.labelName"
            placeholder="请输入标签名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="labelType" label="标签类型：">
          <el-select v-model="formData.labelType">
            <el-option
              v-for="item in options.labelType"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >{{ item.label }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="applyType" label="打标方式：">
          <el-select v-model="formData.applyType" disabled>
            <el-option
              v-for="item in options.applyType"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >{{ item.label }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="subscriptImg" label="商品图角标：">
          <Upload
            :defaultList="defaultList.subscriptImg"
            :maxSize="2048"
            :maxLen="1"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="list => {handleChangeImage(list, 'subscriptImg')}"
          ></Upload>
          <p>提示: 上传图片大小不能超过2048K,尺寸750px*360px</p>
        </el-form-item>
        <el-form-item prop="nameImg" label="商品名称图标：">
          <Upload
            :defaultList="defaultList.nameImg"
            :maxSize="2048"
            :maxLen="1"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="list => {handleChangeImage(list, 'nameImg')}"
          ></Upload>
          <p>提示: 上传图片大小不能超过2048K,尺寸100px*100px，比例1:1</p>
        </el-form-item>
        <el-form-item prop="note" label="标签介绍：">
          <el-input
            v-model="formData.note"
            placeholder="请输入标签介绍"
            type="textarea"
            maxlength="100"
            show-word-limit
            :autosize="{ minRows: 2, maxRows: 5 }"
          />
        </el-form-item>
      </el-form>
      <!-- 按钮操作栏 -->
      <BtnRender :render="renderBtnsBar" />
    </div>
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import Upload from '@/components/common/upload'; // 上传组件
import { getBtnsBar } from '@/utils/getBtnsRender';
import { LABEL_TYPE_OPTIONS, APPLY_TYPE_OPTIONS, APPLY_TYPE_VALUES } from './constants';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  addLabelService,
  updateLabelService,
  queryLabelByIdService
} from '@/api/commodity/commodityManage/productTagManage';
export default {
  components: {
    BtnRender,
    Upload
  },
  data () {
    return {
      formData: {},
      formRules: {
        labelName: [{ required: true, message: '请填写标签名称', trigger: ['change', 'blur'] }],
        labelType: [{ required: true, message: '请选择标签类型', trigger: 'change' }],
        applyType: [{ required: true, message: '请选择打标方式', trigger: 'change' }],
        note: [
          { required: true, message: '请填写标签介绍', trigger: ['change', 'blur'] },
          { type: 'string', min: 5, message: '介绍不得少于5个字符', trigger: 'change' }
        ]
      },
      options: {
        labelType: [...LABEL_TYPE_OPTIONS],
        applyType: [...APPLY_TYPE_OPTIONS]
      },
      btnLoading: {
        submit: false
      },
      defaultList: {
        subscriptImg: [], // 商品图角标
        nameImg: [] // 商品名称图标
      },
      pageId: ''
    }
  },
  computed: {
    pageTitle () {
      if (this.isEditPage) return '编辑标签'
      return '新增标签'
    },
    isEditPage () {
      return !!this.$route?.query?.id
    }
  },
  created () {
    this.pageId = this.$route?.query?.id
    this.queryLabelDetails(this.pageId)
    if (!this.isEditPage) {
      this.formData.applyType = APPLY_TYPE_VALUES.Manual
    }
  },
  methods: {
    // jsx-render渲染按钮操作栏
    renderBtnsBar (h) {
      const basicBtns = [
        { label: '提交', method: this.handleSubmit, type: 'primary', loading: this.btnLoading.submit },
        { label: '返回', method: this.handleGoBack, type: 'default' }
      ]
      const btnList = basicBtns.map(item => ({ ...item, size: 'mini' }))
      return getBtnsBar(h, btnList, null, 'center');
    },
    // 获取标签详情
    async queryLabelDetails (id) {
      if (!id) return
      const res = await queryLabelByIdService({ id }, '.form_body')
      if (res?.retData) {
        this.setLabelDetails(res.retData)
      }
    },
    // 设置标签详情
    setLabelDetails (data) {
      this.formData = _.omit(data, 'id')
      if (data?.subscriptImg) {
        this.defaultList.subscriptImg = [{ url: `/${data.subscriptImg}` }]
      }
      if (data?.nameImg) {
        this.defaultList.nameImg = [{ url: `/${data.nameImg}` }]
      }
    },
    // 提交
    async handleSubmit () {
      this.$refs.formData.validate((valid) => {
        valid ? this.submitLabelData() : this.$message.warning('请按规则填写后提交！')
      });
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'productTagManageList' })
    },
    // 图片变化
    handleChangeImage (list, prop) {
      this.defaultList[prop] = list
      this.formData[prop] = list[0]?.url ?? ''
    },
    // 提交标签表单数据
    async submitLabelData () {
      const reqestFn = this.isEditPage ? updateLabelService : addLabelService
      const data = { ...this.formData, id: this.pageId }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await reqestFn(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.form_body {
  padding-left: 150px;
  padding-right: 200px;
}
</style>
